package com.ly.os;

import java.util.concurrent.Semaphore;

/**
 * @Classname PhilosopherEatQuestionSync
 * @Description TODO
 * @Date 2020/12/7 14:58
 * @Author 冷心影翼
 */
public class PhilosopherEatQuestionSync {

	private Object[] chops = new Object[5];

	private Semaphore semaphore = new Semaphore(4);

	public PhilosopherEatQuestionSync() {
		for(int i=0;i<5;i++) {
			chops[i] = new Object();
		}
	}

	public void eatWithDeadLock() {
		for(int i=0;i<5;i++) {
			int finalI = i;
			new Thread(()->{
				while (true) {
					synchronized (chops[finalI]) {
						synchronized (chops[(finalI+1)%5]) {
							System.out.println(finalI +" eat");
						}
					}
					Thread.yield();
				}
			}).start();
		}
	}

	public void eat1() {
		for(int i=0;i<5;i++) {
			int finalI = i;
			new Thread(()->{
				while (true) {
					try {
						semaphore.acquire();
						synchronized (chops[finalI]) {
							synchronized (chops[(finalI+1)%5]) {
								System.out.println(finalI +" eat");
								semaphore.release();
							}
						}
						Thread.yield();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
	}


	public void eat2() {
		for(int i=0;i<5;i++) {
			int finalI = i;
			new Thread(()->{
				while (true) {
					try {
						if(finalI % 2 == 0) {
							synchronized (chops[finalI]) {
								synchronized (chops[(finalI+1)%5]) {
									System.out.println(finalI +" eat");
								}
							}
						} else {
							synchronized (chops[(finalI+1) % 5]) {
								synchronized (chops[finalI]) {
									System.out.println(finalI + " eat");
								}
							}
						}
						Thread.yield();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
	}

	public static void main(String[] args) {
		PhilosopherEatQuestionSync philosopherEatQuestionSync = new PhilosopherEatQuestionSync();
//		philosopherEatQuestionSync.eatWithDeadLock();
//		philosopherEatQuestionSync.eat1();
		philosopherEatQuestionSync.eat2();
	}
}
